package controllers.weixin;

import auth.WxMpAuth;
import models.contract.ContractCardRelation;
import models.user.User;
import play.mvc.Controller;
import play.mvc.With;
import utils.WxMsgTempUtil;

import java.util.HashMap;
import java.util.Map;

@With(WxMpAuth.class)
public class AccessCardController extends Controller {

    public static void index(String id) {
        renderArgs.put("code",id);
        render();
    }


    /**
     * 绑定银行卡
     * @param cardNumber
     * @param name
     * @param phone
     */
    public static void bind(String cardNumber , String name , String phone , String identityCard) {
        Map<String , Object> resultMap = new HashMap<>();
        User user= WxMpAuth.currentUser();
        resultMap.put("success" , false);
        if (cardNumber == null || "".equals(cardNumber.trim())) {
            resultMap.put("msg" , "卡号不能为空");
            renderJSON(resultMap);
        }
        if (name == null || "".equals(name.trim())) {
            resultMap.put("msg" , "名字不能为空");
            renderJSON(resultMap);
        }
        if (phone == null || "".equals(phone.trim())) {
            resultMap.put("msg" , "手机号不能为空");
            renderJSON(resultMap);
        }
        if (identityCard == null || "".equals(identityCard.trim())) {
            resultMap.put("msg" , "身份证号不能为空");
            renderJSON(resultMap);
        }
        ContractCardRelation contractCardRelation = ContractCardRelation.findByCardNumber(cardNumber);
        if(contractCardRelation == null) {
            resultMap.put("msg" , "该门禁卡未绑定合同");
            renderJSON(resultMap);
        }
//        ContractCardRelation contractCardRelation2  = ContractCardRelation.findByUser(user);
//        if(contractCardRelation2 != null) {
//            resultMap.put("msg" , "该门禁卡已绑定用户");
//            renderJSON(resultMap);
//        }
        String userOpenId = user.openId;
        contractCardRelation.name = name;
        contractCardRelation.phone = phone;
        contractCardRelation.user = user;
        contractCardRelation.identityCard = identityCard;
        contractCardRelation.save();
        System.out.println("------step1");
        // 绑定门禁卡后 user 设置真实姓名和电话
        User entityUser = User.findByUserId(user.id);
        entityUser.realName= name;
        entityUser.phone= phone;
        entityUser.belongCompany = contractCardRelation.belongCompany;
        entityUser.save();
        WxMsgTempUtil.bindAccessCard2(contractCardRelation,userOpenId);

        resultMap.put("success" , true);
        resultMap.put("msg" , "门禁卡绑定成功");
        renderJSON(resultMap);


    }


}
